<?php

namespace app\common\service\FinancialService;

use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Commission;
use app\model\BbcModel\ConfigChannel;
use app\model\BbcModel\Host;
use app\model\BbcModel\Store;
use app\model\BbcModel\ServiceProvider;
use app\model\BbcModel\StoreBudget;
use app\model\BbcModel\StoreWithdraw;
use app\Normal;
use app\common\service\PayService\HnaPay\HnPayClient;


/**
 * 分销商结算统计
 * @author Administrator
 */
class StoreStatisticsService
{

    /**
     * 品牌分销商结算
     * @param array $param
     * @return array
     */
    public function storeList(array $param)
    {
        $where=[];
        if(!empty($param['sp_id'])){
            $where[]=['sp_id','in',$param['sp_id']];
        }
        if(!empty($param['cb_id'])){
            $where[]=['cb_id','in',$param['cb_id']];
        }
        if(!empty($param['mn_sid'])){
            $where[]=['id','in',$param['mn_sid']];
        }
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $service=ServiceProvider::instance()->lists(['_fields_'=>'id,name']);
        $service=array_column($service,'name','id');
        //渠道商列表
        $business=ChannelBusiness::instance()->lists(['_fields_'=>'id,name']);
        $business=array_column($business,'name','id');
        $list=Store::instance()
            ->field('id,sp_id,cb_id,store_name,all_sell,wallet_accumulate_income,frozen_income,withdraw,wallet_income,withdraw_check,status')
            ->where($where)
            ->order('id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        $num=Store::instance()
            ->where($where)
            ->order('id desc')
            ->limit($p, $limit)
            ->count();
        foreach ($list as $k=>$v){
            $list[$k]['service_name']=$service[$v['sp_id']];
            $list[$k]['business_name']=$business[$v['cb_id']];
            $list[$k]['all_commission']=round($v['wallet_accumulate_income']+$v['frozen_income'],2);
            $list[$k]['status_name']=$v['status']?'启用':'禁用';
        }
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 分销商分佣流水
     * @param array $param
     * @return array
     */
    public function orderList(array $param)
    {
        if(empty($param['mn_sid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数mn_sid");
        }
        $where=[
            ['mn_sid','=',$param['mn_sid']],
            ['status','=',1]
        ];
        //子订单号
        if(!empty($param['sn'])){
            $where[]=['sn','like','%'.$param['sn'].'%'];
        }
        //下单时间
        if(!empty($param['cd_start'])){
            $where[]=['md','>=',strtotime($param['cd_start'])];
        }
        if(!empty($param['cd_end'])){
            $where[]=['md','<=',strtotime($param['cd_end'])];
        }
        if(!empty($param['order_type'])){
            $where[]=['order_type','=',$param['order_type']];
        }
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $p=($page-1)*$limit;
        $list=Commission::instance()
            ->field('id,sn,sum(store_money) as money,md,order_type')
            ->where($where)
            ->group('order_id')
            ->order('id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        $num=Commission::instance()
            ->where($where)
            ->group('order_id')
            ->count();
        foreach ($list as $k=>$v){
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['md']);
            $list[$k]['type']=Commission::instance()->order_type[$v['order_type']];
        }
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 分销商提现审核列表
     * @param array $param
     * @return array
     */
    public function withdrawList(array $param)
    {
        $where=[];
        if(!empty($param['sp_id'])){
            $where[]=['sp_id','in',$param['sp_id']];
        }
        if(!empty($param['cb_id'])){
            $where[]=['cb_id','in',$param['cb_id']];
        }
        if(!empty($param['mn_sid'])){
            $where[]=['mn_sid','in',$param['mn_sid']];
        }
        //提现状态
        if(isset($param['status']) && $param['status'] !==0){
            $where[]=['status','=',$param['status']];
        }
        //审核状态
        if(isset($param['check_status']) && $param['check_status'] !==0){
            $where[]=['check_status','=',$param['check_status']];
        }
        //下单时间
        if(!empty($param['cd_start'])){
            $where[]=['cd','>=',strtotime($param['cd_start'])];
        }
        if(!empty($param['cd_end'])){
            $where[]=['cd','<=',strtotime($param['cd_end'])];
        }
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $p=($page-1)*$limit;
        $service=ServiceProvider::instance()->lists(['_fields_'=>'id,name']);
        $service=array_column($service,'name','id');
        //渠道商列表
        $business=ChannelBusiness::instance()->lists(['_fields_'=>'id,name']);
        $business=array_column($business,'name','id');
        $store=Store::instance()->lists(['_fields_'=>'id,store_name']);
        $store=array_column($store,'store_name','id');
        $list=StoreWithdraw::instance()
            ->field('id,sn,sp_id,cb_id,mn_sid,cd,money,status,check_status')
            ->where($where)
            ->order('id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        $num=StoreWithdraw::instance()
            ->where($where)
            ->count();
        foreach ($list as $k=>$v){
            $list[$k]['service_name']=$service[$v['sp_id']];
            $list[$k]['business_name']=$business[$v['cb_id']];
            $list[$k]['store_name']=$store[$v['mn_sid']];
            $list[$k]['status_name']=StoreWithdraw::instance()->status[$v['status']];
            $list[$k]['check_status_name']=StoreWithdraw::instance()->status[$v['check_status']];
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['cd']);
        }
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }


    /**
     * 渠道商提现审核
     * @param array $param
     * @return array
     */
    public function checkWithdraw(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数id");
        }
        if(empty($param['op'])){
            return Normal::returnCode(Normal::FAIL,"操作参数错误");
        }
        if(empty($param['check_user'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数check_user");
        }
        $info=storeWithdraw::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"审核的提现申请不存在");
        }
        if($info['check_status']!=0){
            return Normal::returnCode(Normal::FAIL,"操作提现记录不是待审核状态成功");
        }
        StoreWithdraw::instance()->startTrans();
        $business=Store::instance()->info(['id'=>$info['mn_sid']]);
        $data = [
            'check_time'=>time(),
            'check_status'=>$param['op'],
            'check_user'=>$param['check_user'],
        ];
        if($param['op']==2){
            if(empty($param['check_note'])){
                return Normal::returnCode(Normal::FAIL,"请输入拒绝原因");
            }
            //拒绝通过
            $data['remark']=$param['check_note'];
            $data['status']=$param['op'];
            $wallet_income=$business['wallet_income']+$info['money'];
            $withdraw_check=$business['withdraw_check']-$info['money'];
            Store::instance()->edit(['id'=>$business['id']],['wallet_income'=>$wallet_income,'withdraw_check'=>$withdraw_check]);
            $add['money']=$info['money'];
            $add['sn']=$info['sn'];
            $add['goods_id']=0;
            $add['mid']=$info['mid'];
            $add['mn_sid']=$info['mn_sid'];
            $add['cb_id']=$info['cb_id'];
            $add['type']=1;
            $add['money_type']=5;
            $add['cd']=time();
            $add['amount']=$wallet_income;
            $add['remark']='提现审核失败退款';
            StoreBudget::instance()->add($add);
        }else{
            $pay_way=ConfigChannel::instance()->info(['cid'=>$info['cid'],'code'=>'pay_way']);
            $pay_type=0;
            if(!empty($pay_way) && !empty($pay_way['value'])){
                $value=json_decode($pay_way['value'],1);
                $pay_type=$value['type'];
            }
            if($pay_type==1){
                //新生支付
                $add['pay_type']=9;
                $bank=json_decode($info['bank_info'],true);
                $order_data = [
                    'merOrderId' =>$info['sn'],
                    'payType'=>'1',
                    'auditflag'=>'0',
                    'payeeAcctNo'=>(string)$bank['bankcard'],
                    'payeeName'=>$bank['true_name'],
                    'payeeType'=>$bank['card_type'],
                    'amount' => (int)($info['money']*100),
                    'currencyCode'=>'CNY',
                    'feeType'=>'1',
                    'bankName'=>$bank['bank_name'],
                ];
                if($bank['card_type']==1){
                    $order_data['payeeId']=$bank['idcard'];
                }else{
                    $order_data['payeeId']=$bank['org_code'];
                }
                $config= ConfigChannel::instance()->info(['cid'=>$info['cid'],'code'=>'hnapay_pay']);
                $payconfig=json_decode($config['value'],true);
                $payconfig['cid']=$info['cid'];
                $payconfig['mnid']=2;
                $host =Host::instance()->info(['tob'=>'notify','status'=>1]);
                if(empty($host)){
                    StoreWithdraw::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL,'回调地址未配置');
                }
                $order_data['noticeUrl']=$host['host'].'/master/HnpayReceive/storeWithdraw';
                // 新生提现
                $res= HnPayClient::instance($payconfig)->transfer($order_data);
                \think\facade\Log::write(json_encode($res,JSON_UNESCAPED_UNICODE),'hnapay_transfer');
                if($res['content']['responseCode']=='0000' && $res['content']['status']!=2){
                }else{
                    StoreWithdraw::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL,$res['content']['responseDesc']);
                }
            }else{
                return Normal::returnCode(Normal::FAIL,"微信提现待开发");
            }
        }
        $res1 = StoreWithdraw::instance()->edit(['id'=>$param['id']],$data);
        if(empty($res1)) {
            StoreWithdraw::instance()->rollback();
            return [
                'status' => Normal::FAIL,
                'msg' => '操作失败',
            ];
        }
        StoreWithdraw::instance()->commit();
        return Normal::returnCode(Normal::SUC,"操作成功");
    }

    /**
     * 提现回调
     */
    public function storeWithdraw(array $param)
    {
        $data= $param;
        \think\facade\Log::write($data,'hnapay_withdraw_notify');
        StoreWithdraw::instance()->startTrans();
        try{
            $info=StoreWithdraw::instance()->info(['sn'=>$data['content']['merOrderId']]);
            $store=Store::instance()->info(['id'=>$info['mn_sid']]);
            if($data['content']['responseCode']=="0000" && $data['content']['status']==1){
                $withdraw=$store['withdraw']+$info['money'];
                $withdraw_check=$store['withdraw_check']-$info['money'];
                Store::instance()->edit(['id'=>$store['id']],['withdraw'=>$withdraw,'withdraw_check'=>$withdraw_check]);
                $datas['status']=1;
                $datas['account_time']=time();
                $datas['pay_serial']=$data['content']['dealId']??'';
//                $add['money']=$info['money'];
//                $add['sn']=$info['sn'];
//                $add['cb_id']=$info['cb_id'];
//                $add['goods_id']=0;
//                $add['mid']=0;
//                $add['mn_sid']=$info['mn_sid'];
//                $add['money_type']=4;
//                $add['pay_serial']=$datas['pay_serial'];
//                $add['cid']=$info['cid'];
//                $add['type']=0;
//                $add['cd']=time();
//                $add['remark']='提现支出';
//                StoreBudget::instance()->add($add);
            }else{
                $datas['status']=2;
                $datas['remark']=empty($data['content']['failInfo'])?'打款失败':$data['content']['failInfo'];
                $wallet_income=$store['wallet_income']+$info['money'];
                $withdraw_check=$store['withdraw_check']-$info['money'];
                Store::instance()->edit(['id'=>$info['mn_sid']],['wallet_income'=>$wallet_income,'withdraw_check'=>$withdraw_check]);
                $add['money']=$info['money'];
                $add['sn']=$info['sn'];
                $add['goods_id']=0;
                $add['mid']=$info['mid'];
                $add['cb_id']=$info['cb_id'];
                $add['mn_sid']=$info['mn_sid'];
                $add['type']=1;
                $add['money_type']=5;
                $add['cd']=time();
                $add['amount']=$wallet_income;
                $add['remark']='提现打款失败退款';
                StoreBudget::instance()->add($add);
            }
            StoreWithdraw::instance()->edit(['id'=>$info['id']],$datas);
            StoreWithdraw::instance()->commit();
        }catch (\Exception $e){
            StoreWithdraw::instance()->rollback();
            \think\facade\Log::write( $e->getMessage(),'hnapay_withdraw_notify_fail');
        }
        return Normal::returnCode(Normal::SUC,"操作成功");
    }
}
